package com.shop.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shop.model.Category;

import com.shop.model.Goods;
import com.shop.model.User;
import com.shop.model.common.SearchPage;
import com.shop.model.common.SearchPageGoods;
import com.shop.service.AdminService;
import com.shop.service.CategoryService;
import com.shop.service.GoodsService;
import com.shop.service.UserService;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
@Slf4j
public class AdminController {
    @Autowired
    private UserService userService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private AdminService adminService;

    @GetMapping("/")
    public ModelAndView admin(HttpSession session){
        User user=(User)session.getAttribute("user");
        if(user==null||user.getUserType()==0){
            return new ModelAndView("redirect:/user/login");
        }
        return new ModelAndView("admin/admin");
    }

    @GetMapping("/user/list")
    public ModelAndView userList(HttpSession session){
        User user=(User)session.getAttribute("user");
        if(user==null||user.getUserType()==0){
            return new ModelAndView("redirect:/user/login");
        }
        ModelAndView modelAndView=new ModelAndView();
        SearchPage searchPage=new SearchPage();
        searchPage.setPage(1);
        searchPage.setPageSize(10);
        List<User> list=userService.searchPage(searchPage);
        Integer count = userService.searchCount(searchPage);
        Integer totalPages=count/searchPage.getPageSize()+1;
        if(count%searchPage.getPageSize()==0) totalPages=count/searchPage.getPageSize();
        modelAndView.addObject("userList", list);
        modelAndView.addObject("pageTotal",totalPages);
        modelAndView.addObject("count",count);
        modelAndView.setViewName("admin/admin_list");
        return modelAndView;
    }

    @GetMapping("/user/search")
    public ModelAndView userSearch(@RequestParam Map<String,String> map) {
        log.info("map:{}",map);
        ModelAndView modelAndView=new ModelAndView();

        ObjectMapper objectMapper=new ObjectMapper();
        SearchPage searchPage=objectMapper.convertValue(map, SearchPage.class);
        if(searchPage.getPage()==null) searchPage.setPage(1);
        searchPage.setPageSize(10);
        if("".equals(searchPage.getAccount())) searchPage.setAccount(null);
        if("".equals(searchPage.getEmail())) searchPage.setEmail(null);
        if("".equals(searchPage.getPhone())) searchPage.setPhone(null);
        List<User> list=userService.searchPage(searchPage);
        Integer count = userService.searchCount(searchPage);
        Integer totalPages=count/searchPage.getPageSize()+1;
        if(count%searchPage.getPageSize()==0) totalPages=count/searchPage.getPageSize();
            modelAndView.addObject("userList", list);
        modelAndView.addObject("pageTotal",totalPages);
        modelAndView.addObject("count",count);
        modelAndView.setViewName("admin/admin_list");
        return modelAndView;


    }

    @GetMapping("/user/freeze")
    public ModelAndView userFreeze(@RequestParam Integer id){
        userService.userFreeze(id);
        return new ModelAndView("redirect:/admin/user/list");
    }

    @GetMapping("/user/unfreeze")
    public ModelAndView userUnFreeze(@RequestParam Integer id){
        userService.userUnFreeze(id);
        return new ModelAndView("redirect:/admin/user/list");
    }

    @GetMapping("/user/blacklist/add")
    public ModelAndView blacklistAdd(@RequestParam Integer id){
        userService.blacklistAdd(id);
        return new ModelAndView("redirect:/admin/user/list");
    }

    @GetMapping("/user/blacklist/remove")
    public ModelAndView blacklistRemove(@RequestParam Integer id){
        userService.blacklistRemove(id);
        return new ModelAndView("redirect:/admin/user/list");
    }

    @GetMapping("/user/delete")
    public ModelAndView userDelete(@RequestParam Integer id){
        userService.userDelete(id);
        return new ModelAndView("redirect:/admin/user/list");
    }



    @GetMapping("/admin/list")
    public ModelAndView adminList(){
        ModelAndView modelAndView=new ModelAndView();
        List<User> adminList=adminService.getAll();
        modelAndView.addObject("adminList",adminList);
        modelAndView.setViewName("admin/admin_update");
        return modelAndView;
    }

    @GetMapping("/category/add")
    public ModelAndView categoryAdd(){
        ModelAndView modelAndView=new ModelAndView();
        List<Category> categoryList = categoryService.selectAllCategory();
        modelAndView.addObject("categoryList",categoryList);
        modelAndView.setViewName("admin/category_add");
        return modelAndView;
    }

    @PostMapping("/category/add")
    public ModelAndView categoryAdding(@RequestParam String name,
                                       @RequestParam(required = false) Integer pid,
                                       RedirectAttributes redirectAttributes      ){
        ModelAndView modelAndView=new ModelAndView();

        Boolean flog=categoryService.categoryAdd(name, pid);
        if(flog) redirectAttributes.addFlashAttribute("msg", "分类已存在");
        else redirectAttributes.addFlashAttribute("msg","添加成功");
        return new ModelAndView("redirect:/admin/category/add");
    }

    @GetMapping("/category/list")
    public ModelAndView categoryList(){
        ModelAndView modelAndView=new ModelAndView();
        List<Category> categoryList = categoryService.selectAllCategory();
        modelAndView.addObject("categoryList", categoryList);
        modelAndView.setViewName("admin/category_list");
        return modelAndView;
    }

    @GetMapping("/goods/list")
    public ModelAndView goodsList(){

        ModelAndView modelAndView=new ModelAndView();
        SearchPageGoods searchPage=new SearchPageGoods();
        searchPage.setPage(1);
        searchPage.setPageSize(5);
        List<Goods> list=goodsService.searchPage(searchPage);
        Integer count = goodsService.searchCount(searchPage);
        Integer totalPages=count/searchPage.getPageSize()+1;
        if(count%searchPage.getPageSize()==0) totalPages=count/searchPage.getPageSize();

        List<Category> categoryList=categoryService.selectAllCategory();
        modelAndView.addObject("categoryList",categoryList);
        modelAndView.addObject("goodsList", list);
        modelAndView.addObject("pageTotal",totalPages);
        modelAndView.addObject("count",count);
        modelAndView.setViewName("admin/goods_list");
        return modelAndView;
    }

    @GetMapping("/goods/search")
    public ModelAndView goodsSearch(@RequestParam Map<String, String> map) {

        log.info("map:{}",map);
        ModelAndView modelAndView=new ModelAndView();
        map.put("categoryId",map.get("category"));
        map.remove("category");
        ObjectMapper mapper=new ObjectMapper();
        SearchPageGoods searchPage=mapper.convertValue(map, SearchPageGoods.class);
        if(searchPage.getPage()==null) searchPage.setPage(1);
        searchPage.setPageSize(5);
        if("".equals(searchPage.getStatus())) searchPage.setStatus(null);
        if("".equals(searchPage.getName())) searchPage.setName(null);

        List<Goods> list=goodsService.searchPage(searchPage);
        Integer count = goodsService.searchCount(searchPage);
        log.info("count:{}",count);
        log.info("searchPage:{}", searchPage);

        Integer totalPages=count/searchPage.getPageSize()+1;
        if(count%searchPage.getPageSize()==0) totalPages=count/searchPage.getPageSize();
        List<Category> categoryList=categoryService.selectAllCategory();
        modelAndView.addObject("categoryList",categoryList);
        modelAndView.addObject("goodsList", list);
        modelAndView.addObject("pageTotal",totalPages);
        modelAndView.addObject("count",count);
        modelAndView.setViewName("admin/goods_list");
        return modelAndView;
    }

    @PostMapping("/goods/update")
    public ModelAndView update(@RequestParam Map map){
        log.info("map:{}",map);
        goodsService.update(map);
        return new ModelAndView("redirect:list");
    }

    @GetMapping("/goods/updateStatus")
    public ModelAndView updateStatus(@RequestParam Integer id,@RequestParam String status){
        goodsService.updateStatus(id, status);
        return new ModelAndView("redirect:list");
    }



    @PostMapping("/category/update")
    public ModelAndView categoryUpdate(@RequestParam Map<String, Object> params,RedirectAttributes redirectAttributes){
        log.info("params:{}",params);
        Boolean flog=categoryService.categoryUpdate(params);
        if (!flog)  redirectAttributes.addFlashAttribute("msg", "修改失败，该分类已存在");
        return new ModelAndView("redirect:/admin/category/list");
    }

    @GetMapping("/category/delete")
    public ModelAndView categoryDelete(@RequestParam Integer id,RedirectAttributes redirectAttributes){
        Boolean flog=categoryService.delete(id);
        if (!flog)  redirectAttributes.addFlashAttribute("msg", "删除失败该分类下存在子分类或商品");
        return new ModelAndView("redirect:/admin/category/list");
    }



    @PostMapping("/admin/update")
    public ModelAndView adminUpdate(@RequestParam Integer id,@RequestParam String account,@RequestParam String username,RedirectAttributes redirectAttributes) {

        String phone="^1[3-9]\\d{9}$";
        Boolean isPhone=account.matches(phone);
        if(!isPhone){
            redirectAttributes.addFlashAttribute("msg", "电话号码格式有误");
            return new ModelAndView("redirect:/admin/admin/list");
        }
        Boolean flog=adminService.update(id, account,username);
        if(!flog) redirectAttributes.addFlashAttribute("msg", "该电话号码已被使用");
        return new ModelAndView("redirect:/admin/admin/list");
    }

    @GetMapping("/admin/delete")
    public ModelAndView adminDelete(@RequestParam Integer id){
        adminService.delete(id);
        return new ModelAndView("redirect:/admin/admin/list");
    }

    @PostMapping("/admin/add")
    public ModelAndView adminAdd(@RequestParam String account,RedirectAttributes redirectAttributes){

        String phone="^1[3-9]\\d{9}$";
        Boolean isPhone=account.matches(phone);
        if(!isPhone){
            redirectAttributes.addFlashAttribute("msg", "电话号码格式有误");
            return new ModelAndView("redirect:/admin/admin/list");
        }

        Boolean flag=adminService.add(account);
        return new ModelAndView("redirect:/admin/admin/list");
    }



}
